﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Kristall.Engine;
using Kristall.Engine.Scripts;

namespace Kristall.MyGame.Scripts
{
    public class DoorScript : Script
    {
        Direction Direction
        {
            get;
            set;
        }

        float Speed
        {
            get;
            set;
        }

        public DoorScript()
        {
            Speed = 1000f;
        }

        AABB _aabb;
        Vector2 _startPosition;

        public override void Load(Level level, AABB aabb)
        {
            base.Load(level, aabb);

            _aabb = aabb;
            _startPosition = _aabb.Position;
        }

        public override void Update(float dt)
        {
            base.Update(dt);

            Vector2 targetPosition = _startPosition;

            if (Enabled)
            {
                switch (Direction)
                {
                    case Direction.Top:
                        targetPosition += -Vector2.UnitY * _aabb.Height;
                        break;
                    case Direction.Bottom:
                        targetPosition += Vector2.UnitY * _aabb.Height;
                        break;
                    case Direction.Left:
                        targetPosition += -Vector2.UnitX * _aabb.Width;
                        break;
                    case Direction.Right:
                        targetPosition += Vector2.UnitX * _aabb.Width;
                        break;
                }

            }

            Vector2 direction = targetPosition - _aabb.Position;
            float distance = direction.Length();

            if (distance <= 0.1f)
                return;

            direction.Normalize();

            _aabb.Velocity = direction * Speed;

            if ((_aabb.Velocity * dt).Length() >= distance)
            {
                _aabb.Velocity.Normalize();
                _aabb.Velocity *= distance / dt;
            }

            _aabb.Position += _aabb.Velocity * dt;
        }
    }
}
